package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.MathProblem;

/**
 * 172 233
 * 过了, 写的好丑
 *
 * @author tzp
 * @since 2020/11/18
 */
public class LC233 implements MathProblem {
    public int countDigitOne(int n) {
        int maxP = (int) Math.pow(10, 9);
        int powTen = 10;
        int result = 0;
        while (n >= powTen / 10) {
            int i = n / powTen;
            int j = n % powTen;
            result += i * powTen / 10;

            if (j >= 2 * powTen / 10 - 1) {
                result += powTen / 10;
            } else if (j >= powTen / 10) {
                result += j - powTen / 10 + 1;
            }
            if (powTen == maxP) {
                break;
            }
            powTen *= 10;
        }
        if (n >= maxP) {
            if (n >= 2 * maxP - 1) {
                result += maxP;
            } else if (n >= maxP) {
                result += n - maxP + 1;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(new LC233().countDigitOne(824883294));//2042
        System.out.println(new LC233().countDigitOne(3210));//2042
        System.out.println(new LC233().countDigitOne(3211));//2044
        System.out.println(new LC233().countDigitOne(9));
        System.out.println(new LC233().countDigitOne(19));//12
        System.out.println(new LC233().countDigitOne(119));//52
    }
}
